<template>
  <div class="fieldManage zy-content ">
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
        <div>
          <p class="label">功能位置</p>
          <div class="ipt">
            <Cascader clearable :data="orgList" v-model="searchParams.factoryCode" change-on-select placeholder="请选择">
            </Cascader>
          </div>
        </div>
        </Col>
        <Col span="4">
        <div>
          <p class="label">班组</p>
          <div class="ipt">
            <Select v-model="searchParams.team" filterable clearable :placeholder="`${$t('common.selectInfo')}`"
              @on-change="paramsFactorySelectChange">
              <Option v-for="(item, index) of teamList" :value="item.team" :key="index">{{
                item.team }}
              </Option>
            </Select>
          </div>
        </div>
        </Col>
        <Col span="4">
        <div>
          <p class="label">{{ $t('班次') }}</p>
          <div class="ipt">
            <Input type="text" v-model="searchParams.shift" :placeholder="`${$t('common.inputInfo')}`"></Input>
          </div>
        </div>
        </Col>
        <Col span="4">
        <div>
          <p class="label">班次时间</p>
          <div class="ipt">
          <DatePicker type = 'daterange' :value="searchParams.shiftTime"
                @on-change="(val) => searchParams.shiftTime = val "  format="yyyy-MM-dd"
                placeholder="请选择日期" />
          </div>
        </div>
        </Col>
        <Col span="4">
        <div>
          <p class="label hide-label">--</p>
          <div class="ipt">
            <Button class="search-btn" type="primary" @click="changeNum()">
              {{ $t('common.Query') }}
            </Button>
            <Button class="reset-btn" @click="reset()">{{ $t('common.reset') }}
            </Button>
          </div>
        </div>
        </Col>
      </Row>
    </div>
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>
        <Button @click="showAddModal">{{ $t('common.New') }}</Button>
        <Button @click="exportExcel">{{ $t('common.Export') }}</Button>
      </div>

      <div class="tableContent">
        <Table ellipsis ref="selection" class="resizable-table" border @on-column-width-resize="onColumnWidthResize"
          :columns="columns" :data="tableData" @on-selection-change="onSelectChange">
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn" @click="showAddModal(row)"><i class="iconfont zy-common-bianji"></i>{{
              $t('common.Edit') }}</span>
            <span class="operationBtn" @click="(deleteModal = true), (deleteIds = row.id)"><i
                class="iconfont zy-common-shanchu"></i>{{ $t('common.Delete') }}</span>
          </template>
        </Table>
      </div>

      <Modal :mask-closable="false" v-model="addModal" :title="addtitle" class="modal-content-layout">
        <Form ref="form" class="formList" :model="formItem" label-position="top" :rules="ruleValidate">
          <Row :gutter="20">
            <Col span="12">
            <FormItem label="日期" prop="scheduleDate">
              <DatePicker :value="formItem.scheduleDate" type="daterange" format="yyyy-MM-dd" placeholder="选择日期"
                @on-change="val => { formItem.scheduleDate = val }"></DatePicker>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="功能位置" prop="factoryCode">
              <Cascader clearable :data="orgList" @on-change="factoryCodeChange" v-model="formItem.factoryCode" change-on-select placeholder="请选择">
              </Cascader>
            </FormItem>
            </Col>
          </Row>
          <Row :gutter="20">
             <Col span="12">
            <FormItem label="班组" prop="team">
              <Select v-model="formItem.teamId" clearable @on-change="teamChange"
                :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="( item, index ) of  teamList " :value="item.id" :key="index">{{
                  item.team }}
                </Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="班次" prop="shift">
              <Select v-model="formItem.shiftId" clearable :placeholder="`${$t('common.selectInfo')}`"
                @on-change="shiftChange">
                <Option v-for="( item, index ) of  shiftList " :value="item.id" :key="index">{{
                  item.shift }}
                </Option>
              </Select>
            </FormItem>
            </Col>
          </Row>
          <Row :gutter="20">
            <Col span="12">
            <FormItem label="班次开始时间" prop="shiftStartTime">
              <TimePicker readonly type="time" v-model="formItem.shiftStartTime" value-format="yyyy-MM-dd"
                :placeholder="`${$t('common.selectInfo')}开始时间`" />
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="班次结束时间" prop="shiftEndTime">
              <TimePicker readonly type="time" :value="formItem.shiftEndTime" value-format="yyyy-MM-dd"
                :placeholder="`${$t('common.selectInfo')}结束时间`" />
            </FormItem>
            </Col>
          </Row>
          <Row :gutter="20">
            <Col span="24">
            <FormItem label="备注" prop="remarks">
              <Input type="text" maxlength="200" v-model="formItem.remarks"
                :placeholder="`${$t('common.inputInfo')}`"></Input>
            </FormItem>
            </Col>

          </Row>
        </Form>
        <div slot="footer">
          <Button type="default" @click="addModal = false">{{
            $t("common.Cancle")
          }}</Button>
          <Button type="primary" :loading="loading" @click="addOk('form')">{{
            $t("maintenance.Confirmed")
          }}</Button>
        </div>
      </Modal>

      <div class="pageWrap mt16">
        <pageLeftTitle :total="pageHelper.total" :selected="tableDataIdList.length" />
        <Page :total="pageHelper.total" :page-size="pageHelper.pageSize" :page-size-opts="$variable.pageSizes"
          :current="pageHelper.pageNum" @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer
          show-total />
      </div>
    </div>
    <Modal :mask-closable="false" v-model="deleteModal" :title="$t('common.Delete')" class="modal-title-layout">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t('common.confirmDelete') }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="deleteModal = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" :loading="delLoading" @click="deleteOk">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { queryPage, exportExcel, deleteApi } from '@/api/system/production-input/production-schedule.js'
import { getTeamList } from '@/api/system/production-input/production-shift.js'
import { findOrgByToken } from "@/api/index.js";
import recursion from "@/util/recursion";
import fileDownload from "js-file-download";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "ProductionSchedule",
  mixins: [toggleTableOperation],
  data() {
    return {
      searchParams: {},
      deleteModal: false,
      columns: [
        {
          key: "selection",
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          title: `${this.$t('common.Date')}`,
          key: 'scheduleDate',
          minWidth: 250,
          align: 'center',
          resizable: true,
          render: (h, params) => {
              return h('div',`${params.row.scheduleDate} 至 ${params.row.scheduleEndDate}`)
          },
        },
        {
          title: '功能位置',
          key: 'factoryName',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
          title: '班组',
          key: 'team',
          minWidth: 120,
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('班次')}`,
          key: 'shift',
          align: 'center',
          minWidth: 400,
          resizable: true
        },
        {
          title: '开始时间',
          key: 'shiftStartTime',
          minWidth: 200,
          align: 'center',
          resizable: true
        },
        {
          title: '结束时间',
          key: 'shiftEndTime',
          minWidth: 200,
          align: 'center',
          resizable: true
        },
        {
          title: '总时长（H）',
          key: 'shiftTotalHourTime',
          align: 'center',
          minWidth: 250,
          resizable: true
        },
        {
          title: '计划产量',
          key: 'planPeopleNumber',
          minWidth: 150,
          align: 'center',
          resizable: true
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: 'action',
          align: 'center',
          fixed: "right",
          width: 180
        }
      ],
      ruleValidate: {
        scheduleDate: [{ required: true, message: `${this.$t('common.selectInfo')}`, trigger: 'change', type: 'array' }],
        factoryCode: [{ required: true, message: `${this.$t('common.selectInfo')}`, trigger: 'change', type: 'array' }],
        shift: [{ required: true, message: `${this.$t('common.selectInfo')}`, type: 'string' }],
        time: [{ required: true, message: `${this.$t('common.inputInfo')}`, trigger: 'change', type: 'array' }],
      },
      tableData: [],
      pageSizeOption: [10, 20, 30, 40],
      pageHelper: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
      },
      addModal: false,
      formItem: {
        scheduleDate: '',
      },
      loading: false,
      checkBtnPermission: {},
      companyList: [],
      orgList: [],
      productionLineList: [],
      tableDataIdList: [],
      importExcelState: false,
      shiftList: [],
      deleteIds: '',
      delLoading: false,
    }
  },
  created() {
    this.getColumnWidth(this.columns)
    // this.getShiftList()
  },
  methods: {
    deleteOk() {
      this.deleteModal = true;
      let params = { id: this.deleteIds }
      deleteApi(params).then(res => {
        this.deleteModal = false;
        if (res.code === 200) {
          this.changeNum();
          this.$Message.success("删除成功");
          this.deleteModal = false;
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      })
    },
    getShiftList(factoryCode) {
      this.axios({
        method: "post",
        url: "/dms/productionSchedule/getShiftByName",
        data: {
          id: '',
          factoryCode,
        }
      }).then((res) => {
        this.shiftList = res.data;
      });
    },
    shiftChange(val) {
      const res = this.shiftList.find((item) => item.id === val);
      this.formItem.shiftStartTime = res.shiftStartTime;
      this.formItem.shiftEndTime = res.shiftEndTime;
      this.formItem.shift = res.shift;
      this.$set(this.formItem, "shift", res.shift);
    },
    teamChange(val) {
      const res = this.teamList.find((item) => item.id === val);
      this.$set(this.formItem, "team", res.team)
    },
    factoryCodeChange(val){
      if (val && val.length!==0) {
       this.getShiftList([val.at(-1)]);
      } else this.getShiftList(null)
    },
    changeTime(data,type) {
      if (data.scheduleDate && data.scheduleDate.length !== 0) {
        if (type == "add") {
          data.scheduleEndDate = data.scheduleDate[1];
          data.scheduleDate = data.scheduleDate[0];
        } else {
          data.scheduleDate = [data.scheduleDate,data.scheduleEndDate];
        }
      } else return;
    },
    addOk(name) {
      this.$refs[name].validate((valid) => {
        if (!valid) {
          return
        } else {
          this.loading = true;
          const data={
            ...this.formItem,
          }
          delete data.time;
          if (data.id) {
            this.changeTime(data,'add');
            this.axios({
              method: "put",
              url: "/dms/productionSchedule/updateSchedule",
              data,
            }).then((res) => {
              this.loading = false;
              if (res.code === 200) {
                this.changeNum();
                this.$Message.success(res.msg);
                this.addModal = false;
                this.loading = false;
              } else {
                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
              }
            });
          } else {
            this.changeTime(data,'add');
            this.axios({
              method: "post",
              url: "/dms/productionSchedule/addSchedule",
              data,
            }).then((res) => {
              this.loading = false;
              if (res.code === 200) {
                this.changeNum();
                this.$Message.success(res.msg);
                this.addModal = false;
                this.loading = false;
              } else {
                this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
              }
            });
          }
        }
      })
    },
    reset() {
      this.searchParams = {};
      this.changeNum();
    },
    changeNum() {
      this.pageHelper.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageHelper.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageHelper.pageNum = val;
      this.searchList();
    },
    async showAddModal(row) {
      this.$refs['form'].resetFields()
      this.formItem = JSON.parse(JSON.stringify(row));
      if (row.id) {
        this.addtitle = `${this.$t('common.Edit')}`
        this.addModal = true
        this.changeTime(this.formItem,'edit');
        setTimeout(()=>{
          this.formItem.shiftId=row.shiftId;
        },300)
        this.factoryCodeChange(row.factoryCode)
      } else {
        this.$refs['form'].resetFields()
        this.addtitle = `${this.$t('common.New')}`
        this.formItem = {
          scheduleDate: '',
        }
        this.addModal = true
      }
    },
    searchList() {//查询列表
      let params = {
        pageNum: this.pageHelper.pageNum,
        pageSize: this.pageHelper.pageSize,
        ...this.searchParams
      };
      if (params.factoryCode && params.factoryCode.length !== 0) {
        params.factoryCode = [params.factoryCode[params.factoryCode.length - 1]]
      }
      if (params.shiftTime && params.shiftTime.length !== 0) {
        params.startTime = params.shiftTime.at(0)
        params.endTime = params.shiftTime.at(-1)
        delete params.shiftTime
      }
      
      queryPage(params).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pageHelper.total = res.data.total
        } else {
          this.$Message.warning(({ content: res.msg, duration: 6, closable: true }));
        }
      })
    },
    onSelectChange(selection) {
      this.tableDataIdList = selection.map((item) => item.id);
    },
    exportExcel() {
      // let params = {
      //   ...this.searchParams,
      //   ids: this.tableDataIdList
      // }
      exportExcel().then(res => {
        fileDownload(res, '生产排班.xlsx');
      })
    },
    getTeam() {
      getTeamList().then((res) => {
        if (res.code === 200) {
          this.teamList = res.data;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    getOrgList() {
      let params = {
        level: 0,
      };
      findOrgByToken(params).then((res) => {
        if (res.code === 200) {
          const obj = {
            label: "name",
            value: "code",
            children: "children",
          };
          this.orgList = recursion.convertTree(res.data, obj);
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      });
    },
    //导出
    exportTemplateClick() {
      let params = {
        belongCompanyId: this.searchParams.belongCompanyId,
        orgId: this.searchParams.orgId,
        deviceNo: this.searchParams.deviceNo,
        deviceName: this.searchParams.deviceName,
        ids: this.deleteIds,
      };
      const filName = this.$t('生产节拍');
      this.axios({
        method: "post",
        url: "/dms/interval/exportData",
        responseType: "blob",
        data: params,
      }).then((res) => {
        fileDownload(res, filName + ".xlsx");
      });
    },
    importExcelChange(val) {
      this.importExcelState = false;
      if (val === "success") {
        // this.$Message.success("导入成功");
        this.changeNum();
      }
    },
  },
  mounted() {
    this.searchList();
    this.getOrgList();
    this.getTeam();
  }
}
</script>

<style scoped lang="scss">
.fieldManage {
  .formList {
    padding: 30px;

    .btn {
      margin-top: 20px;
      text-align: center;
      width: 100%;
      height: 40px;
    }

    .inputBorder {
      border: 1px solid #dcdee2;
      border-radius: 4px;
    }
  }
}
</style>

<style lang="scss"></style>
